#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        
        vector<int> result;
        func(matrix,0,0,matrix.size()-1,matrix[0].size()-1,result);
        return result;

    }
    void func(vector<vector<int>>& matrix,int startrow,int startcol,int endrow,int endcol,vector<int>& result)
    {
        if(startrow>endrow||startcol>endcol){
            return;
        }
        //先计算第一行
        for(int i = startcol;i<=endcol;++i){
            result.push_back(matrix[startrow][i]);
        }
        //计算后一列
        for(int i = startrow+1;i<=endrow;++i){
            result.push_back(matrix[i][endcol]);
        }
        for(int i = endcol-1;i>=startcol&&(endrow!=startrow);--i){
            result.push_back(matrix[endrow][i]);
        }
        for(int i = endrow-1;i>startrow&&(endcol!=startcol);--i){
            result.push_back(matrix[i][startcol]);
        }

        func(matrix,startrow+1,startcol+1,endrow-1,endcol-1,result);
    }

};

int main(){
    vector<vector<int>> matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    Solution S;
    vector<int> result = S.spiralOrder(matrix);
    return 0;
}